package com.coder520.login.controller;

import com.coder520.common.utils.SecurityUtils;
import com.coder520.user.entity.User;
import com.coder520.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * Created by vern on 2017/9/13.
 */

@Controller
@RequestMapping("login")
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     *登录页面
     * @return
     */
    @RequestMapping
    public String login(){
        return "login";
    }

    /**
     * 校验登录
     * @param request
     * @return
     */
    @RequestMapping("check")
    @ResponseBody
    public String checkLogin(HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String username = request.getParameter("username");
        String pwd = request.getParameter("password");
        //查数据库 如果查到数据  调用MD5加密对比密码
        User user = userService.findUserByusername(username);
        if(user!=null){
            //校验成功,返回结果为true
            if(SecurityUtils.checkpassword(pwd,user.getPassword())){
                //设置session
                request.getSession().setAttribute("userinfo",user);
                return "login_succ";
            }else {
                //校验失败 返回校验失败signal
                return "login_fail";
            }
        }else {
            return "login_fail";
        }
    }


    /**
     * 前端使用postman处理传递给后台的json数据
     * 新增用户，MD5处理密码加密
     * @param user
     * @return
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */
    @RequestMapping("register")
    @ResponseBody
    public String register(@RequestBody User user) throws UnsupportedEncodingException, NoSuchAlgorithmException {
       userService.creatUser(user);
        return "succ";
    }
}
